package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.OutputBill;
import com.tianxin.workbao.workBao.bean.OutputBillDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.DateUtilLast;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/7/25.
 */

public class OutputProvide extends BaseDataProvide {
    private Integer mPage = 1;
    private List<OutputBill> outputBillList;
    private OutputBill mOutputBill;
    private UpdateListViewListener mUpdateListViewListener;
    private OutputBillDao outputBillDao;
    private int dataType;
    private int mStatus;
    private boolean isGetData = true;
    private boolean isStatistic = false;

    public OutputProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        outputBillDao = mGreenDaoHelper.getDaoSession().getOutputBillDao();
    }


    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        if (outputBillList != null && !outputBillList.isEmpty()) {
                            outputBillList.clear();
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    outputBillList = JSON.parseArray(dataJson, OutputBill.class);
                                    refreshUI();
                                    if (isStatistic == false) {
                                        saveToDb(outputBillList);
                                    }
                                } else {
                                    mOutputBill = JSON.parseObject(dataJson, OutputBill.class);
                                    if (isGetData) {
                                        refreshUI();
                                    } else {
                                        mUpdateListViewListener.showMessage("oK");
                                    }
                                    if (isStatistic == false) {
                                        saveToDb(mOutputBill);
                                    }
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("output To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {

        if (obj instanceof List) {
            for (int i = 0; i < outputBillList.size(); i++) {
                outputBillDao.insertOrReplace(outputBillList.get(i));
            }
        } else {
            outputBillDao.insertOrReplace((OutputBill) obj);
        }
    }

    /**
     * update the output bill  data  from server
     */
    private void updateFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("dataType", dataType + "");
        map.put("page", mPage + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getOutputBillsUrl(), params), getDisposeDataHandle());

    }

    public void getdatas(int dataType, int currPage) {
        mPage = currPage;
        isGetData = true;
        this.dataType = dataType;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb(currPage);
        } else {
            updateFromServer();
        }
        refreshUI();
    }

    private void getFromDb(int page) {
        Date start = null;
        Date end = null;
        Date date = new Date();
        switch (dataType) {
            case Constant.TODAY_DATA:
                start = DateUtilLast.getStartTime();
                end = DateUtilLast.getEndTime();
                break;
            case Constant.WEEK_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfWeek(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfWeek(date));
                break;
            case Constant.MONTH_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfMonth(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfMonth(date));
                break;
            case Constant.SEASON_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfQuarter(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfQuarter(date));
                break;
            case Constant.YEAR_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getCurrYearFirst());
                end = date;
                break;
        }
        OutputBillDao billDao = GreenDaoHelper.newInstance().getDaoSession().getOutputBillDao();
        Query<OutputBill> query = billDao.queryBuilder().where(OutputBillDao.Properties.Isis.eq(1))
                .where(OutputBillDao.Properties.Addtime.gt(start))
                .where(OutputBillDao.Properties.Addtime.lt(end))
                .orderDesc(OutputBillDao.Properties.Addtime)
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        outputBillList = query.list();
    }

    @Override
    public void refreshUI() {
        if (outputBillList != null && !outputBillList.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(outputBillList);
            } else {
                mUpdateListViewListener.onRefreshData(outputBillList);
            }
        } else {
            mUpdateListViewListener.onRefreshData(mOutputBill);
        }
    }

    public void getBackBill(int status, int currPage) {
        mPage = currPage;
        isGetData = true;
        this.mStatus = status;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getBackBillFromDb(mPage);
            refreshUI();
        } else {
            updateBackBillFromServer();
        }

    }

    private void getBackBillFromDb(int page) {
        Query<OutputBill> query = outputBillDao.queryBuilder().where(OutputBillDao.Properties.Isis.eq(1))
                .where(OutputBillDao.Properties.Isreceived.gt(mStatus))
                .orderDesc(OutputBillDao.Properties.Id)
                .offset((page - 1) * Constant.BACK_BILL_PAGE_SIZE)
                .limit(Constant.BACK_BILL_PAGE_SIZE)
                .build();
        outputBillList = query.list();
    }

    /**
     * update the output bill data  from server
     */
    private void updateBackBillFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("received", mStatus + "");
        map.put("page", mPage + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getBackBillUrl(), params), getDisposeDataHandle());
    }

    /**
     * save back bill 回单录入
     *
     * @param mOutputBill
     */
    public void backBillInput(OutputBill mOutputBill) {
        isGetData = false;
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("output", JSON.toJSONString(mOutputBill));
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getSaveBackBillUrl(), params), getDisposeDataHandle());
    }

    public void getOutPutBillByNumber(String number) {
        isGetData = true;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));

        } else {
            String url = URL.getOutPutBillByNumUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("obnum", number);
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        }

    }

    public void search(String query) {
        if (outputBillList != null) {
            outputBillList.clear();
            mPage = 1;
        }
        String where = "";
        if (StringUtils.isHasChineseChar(query)) {
            where = "(buycompany like '%" + query + "%' or coaltype like '%" + query + "%' ) and isreceived = " + mStatus;
        } else if (StringUtils.isNumber(query)) {
            where = "carnumber like '%" + query + "%' and isreceived = " + mStatus;
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<OutputBill> userQuery = outputBillDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderDesc(OutputBillDao.Properties.Addtime)
                .build();
        outputBillList = userQuery.list();
        refreshUI();
    }

    public void searchTwo(String query) {
        if (outputBillList != null) {
            outputBillList.clear();
            mPage = 1;
        }
        String where = "";
        if (StringUtils.isHasChineseChar(query)) {
            where = "buycompany like '%" + query + "%' or coaltype like '%" + query + "%' ";
        } else if (StringUtils.isNumber(query)) {
            where = "carnumber like '%" + query + "%' and isreceived = ";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<OutputBill> userQuery = outputBillDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderDesc(OutputBillDao.Properties.Addtime)
                .build();
        outputBillList = userQuery.list();
        refreshUI();
    }

    public void getStatistic(Integer dataType) {
        isStatistic = true;
        isGetData = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getCoalStatisticUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("type", dataType + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void getNoOauthDatas(int oauthStatus, int currPage) {
        isGetData = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getOutNoOauthBillUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("page", currPage + "");
            map.put("oauth", oauthStatus + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void oauth(int id) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getOutOauthUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("id", id + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }
}
